package com.netease.xone.widget;

import media.MediaPlayerWrapper;
import media.MediaPlayerWrapper.MediaListener;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.netease.framework.widget.CustomAlertDialog;
import com.netease.image.util.ImageUtil;
import com.netease.pkgRelated.XoneConsts;
import com.netease.xone.R;
import com.netease.xone.activity.ActivityImageProcess;
import com.netease.xone.fragment.FragmentBase;
import com.netease.xone.itemview.RenderInfoAudio;
import com.netease.xone.widget.ViewPagerChild.onEmoticonClickListener;

public class DiscussEditWrapper  implements OnClickListener, TextWatcher, MediaListener{
	
	/**
	 * 可输入最大字符数
	 */
	public int TEXT_MAX_LENGTH = 2000;
	
	/**
	 * 剩余100个开始提示
	 */
    public int mRemainTextLen = 100;
			
	private Activity mActivity = null;
	private FragmentBase mFragment = null;
	private ViewGroup mRootView = null;
	
	private EmoticonEdit mEmoticonEdit = null;
	private TextView mTextViewCount;
	private TextView mAnimTextView;
	private TextView mRecorderDuration;
	private MediaPlayerWrapper mMediaPlayer;
    private AnimationDrawable mAnimationDrawable;
	
	private InputMethodManager mImm;
	
	
	public DiscussEditWrapper(FragmentBase fragment, ViewGroup root) {
	    this(fragment.getActivity(), root);
	    this.mFragment = fragment;
	}
	
	private DiscussEditWrapper(Activity activity, ViewGroup root) {
		if (null == activity || null == root) {
			throw new IllegalArgumentException();
		}
		
		this.mActivity = activity;
		this.mRootView = root;
		init();
	}

	private void init() {
		mImm = (InputMethodManager)mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
		
		mEmoticonEdit = (EmoticonEdit)mRootView.findViewById(R.id.send_edit_postmessage);
		mTextViewCount = (TextView)mRootView.findViewById(R.id.EmotEdit_count);
		mRecorderDuration = (TextView)mRootView.findViewById(R.id.discuss_voice_time);
		
		mRootView.findViewById(R.id.discuss_media).setVisibility(View.GONE);
		mRootView.findViewById(R.id.discuss_voice).setVisibility(View.GONE);
		mRootView.findViewById(R.id.picture).setVisibility(View.GONE);
		
		mEmoticonEdit.setOnClickListener(this);
		mEmoticonEdit.addTextChangedListener(this);
		
		mRootView.findViewById(R.id.voice_delete).setOnClickListener(this);
		
		mAnimTextView = (TextView)mRootView.findViewById(R.id.discuss_voice_anim);
        mAnimTextView.setOnClickListener(this);
        Drawable[] drawables = null;
        drawables = mAnimTextView.getCompoundDrawables();
        mAnimationDrawable = (AnimationDrawable)drawables[0];
		changeTitle(TEXT_MAX_LENGTH);
	}
	
	@Override
	public void onClick(View v) {
		Intent intent = null;
		ViewTag tag = null;
		
		switch (v.getId()) {
		case R.id.send_edit_postmessage:
			if (null != mButtonOnClickListener) {
			    mButtonOnClickListener.onClick(v);
			}
			break;
		case R.id.discuss_voice_anim:
            if (v.isSelected()) {
                tag = (ViewTag)v.getTag();
                v.setSelected(false);
                mAnimationDrawable.stop();
                mAnimationDrawable.start();
                if (null == mMediaPlayer) {
                    mMediaPlayer = MediaPlayerWrapper.getInstance();
                }
                mMediaPlayer.setFilePath(tag.path);
                mMediaPlayer.registerMediaListener(this);
                mMediaPlayer.play();
            } else {
                v.setSelected(true);
                mAnimationDrawable.stop();
                if (null != mMediaPlayer) {
                    mMediaPlayer.stop();
                }
            }
		    break;
		case R.id.voice_delete:
		    // 提示是否删除录音
            CustomAlertDialog.showAlertDialog(mActivity, 0, -1,
                    R.string.discuss_voice_del_title, -1, R.string.discuss_voice_del,
                    R.string.cancel, new CustomAlertDialog.DialogListener() {

                        @Override
                        public void onClick(DialogInterface DialogListn, int which, int key,
                                View view) {
                            if (which == DialogInterface.BUTTON_POSITIVE) {
                                ViewTag tag = null;
                                tag = new ViewTag();
                                tag.flag = false;
                                onProcessRecorder(tag);
                                if (null != mMediaPlayer) {
                                    mMediaPlayer.stop();
                                }
                            }
                        }
                    });
		    break;
		case R.id.picture:
			if (v.getTag() instanceof ViewTag) {
				tag = (ViewTag)v.getTag();
				intent = new Intent(mActivity, ActivityImageProcess.class);
				intent.putExtra(XoneConsts.EXTRA_PATH, tag.path);
				intent.putExtra(XoneConsts.EXTRA_OPERATE, true);
				intent.putExtra(XoneConsts.EXTRA_DURATION, tag.duration);
				intent.setData(tag.imageUri);
				mFragment.startActivityForResult(intent, XoneConsts.RESULT_IMAGE_PREVIEW);
			}
			break;
		default:
		    if (null == v.getTag()) {
		        immControl(false);
		    } else if (v.getTag() instanceof ViewTag) {
		        if (true == ((ViewTag)v.getTag()).flag) {
		            immControl(true);
		        } else if (false == ((ViewTag)v.getTag()).flag) {
		            immControl(false);
		        }
		    }
			break;
		}
	}

	private void setImageVisibility(int visibility) {
	    mRootView.findViewById(R.id.picture).setVisibility(visibility);
	    setMediaVisibility(visibility);
	}
	
	private void setRecorderVisibility(int visibility) {
        mRootView.findViewById(R.id.discuss_voice).setVisibility(visibility);
        setMediaVisibility(visibility);
    }
	
	private void setMediaVisibility(int visibility) {
	    if (View.VISIBLE == visibility) {
	        mRootView.findViewById(R.id.discuss_media).setVisibility(View.VISIBLE);
	    } else {
	        if (View.GONE == mRootView.findViewById(R.id.discuss_voice).getVisibility()
	                && View.GONE == mRootView.findViewById(R.id.picture).getVisibility()) {
	            mRootView.findViewById(R.id.discuss_media).setVisibility(View.GONE);
	        }
	    }
	}
	
	private void onProcessImage(ViewTag tag) {
		ImageView imageView = (ImageView)mRootView.findViewById(R.id.picture);
		if (tag.flag) {
			int width = mActivity.getResources().getDimensionPixelSize(R.dimen.discuss_size_50);
			imageView.setImageBitmap(ImageUtil.getRoundedCornerBitmap(ImageUtil.getBitmapFromFileLimitSize(tag.path, width), -1));
			imageView.setTag(tag);
			imageView.setOnClickListener(this);
			setImageVisibility(View.VISIBLE);
		} else {
		    imageView.setTag(null);
			imageView.setOnClickListener(null);
			setImageVisibility(View.GONE);
		}
	}

	private void onProcessRecorder(ViewTag tag) {
	    if (tag.flag) {
	        mAnimTextView.setTag(tag);
	        setRecorderVisibility(View.VISIBLE);
	        ViewGroup.LayoutParams params = mAnimTextView.getLayoutParams();
	        params.width = RenderInfoAudio.getWidthByDuration(mActivity, tag.duration);
	        mAnimTextView.setLayoutParams(params);
	        mRecorderDuration.setText(tag.duration/1000 + "\"");
	    } else {
	        mAnimTextView.setTag(null);
            setRecorderVisibility(View.GONE);
	    }
	}
	
	public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
		boolean bRes = true;

		do {
			if (resultCode != Activity.RESULT_OK ) {
				bRes = false;
				break;
			}

			switch (requestCode) {
			case XoneConsts.RESULT_IMAGE_PREVIEW:
				ViewTag tag = new ViewTag();
				tag.flag = data.getBooleanExtra(XoneConsts.EXTRA_OPERATE, false);
				tag.path = data.getStringExtra(XoneConsts.EXTRA_PATH);
				tag.duration = data.getIntExtra(XoneConsts.EXTRA_DURATION, 0);
				tag.imageUri = data.getData();
				onProcessImage(tag);
				break;
			case XoneConsts.RESULT_IMAGE_RECORDER:
			    tag = new ViewTag();
                tag.flag = data.getBooleanExtra(XoneConsts.EXTRA_OPERATE, false);
                tag.path = data.getStringExtra(XoneConsts.EXTRA_PATH);
                tag.duration = data.getIntExtra(XoneConsts.EXTRA_DURATION, -1);
                onProcessRecorder(tag);
			    break;
			default:
				bRes = false;
				break;
			}
		} while (false);
		return bRes;
	}

	public void clear() {
		mActivity = null;
		mRootView = null;
		
		mEmoticonEdit = null;
		mTextViewCount = null;
		
		mImm = null;
		mEmoticonClickListener = null;
		if (null != mMediaPlayer) {
		    mMediaPlayer.removeMediaListener(this);
		    mMediaPlayer.release();
		}
		mMediaPlayer = null;
	}

	/** 是否显示软键盘 */
	private void immControl(boolean bShow) {
		if (mImm == null)
			return;

		if (bShow) {
		    mImm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
		} else {
			mImm.hideSoftInputFromWindow(mEmoticonEdit.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

	private void changeTitle(int len){
		String str = "" + len;
		int visible = View.GONE;

		if (len < 0) {
			visible = View.VISIBLE;
		} else if (len <= mRemainTextLen) {
			visible = View.VISIBLE;
		}
		
		mRootView.findViewById(R.id.edit_bottom).setVisibility(visible);
		
		mTextViewCount.setText(str);
	}
	
	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		
	}

	@Override
	public void afterTextChanged(Editable s) {
		int len = s.length();
		
		changeTitle(TEXT_MAX_LENGTH - len);
	}
	
	public OnClickListener getOnButtonClickListener() {
		return this;
	}
	
	private OnClickListener mButtonOnClickListener = null;
    public void setOnButtonClickListener(OnClickListener l) {
        mButtonOnClickListener = l;
    }
	
	public onEmoticonClickListener getEmoticonClickListener() {
		return mEmoticonClickListener;
	}
	
	private onEmoticonClickListener mEmoticonClickListener = new onEmoticonClickListener() {

		@Override
		public void onClick(String phrase) {
		   
			EditText editText = null;
			editText = (EditText) mRootView.findViewById(R.id.send_edit_postmessage);
			
            if ("[删除]".equals(phrase)) {
                editText.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
                return;
            }
            
			int start = editText.getSelectionStart();
			int end = editText.getSelectionEnd();
			Editable txt = editText.getText();
			int min = Math.min(start, end);
			int max = Math.max(start, end);
			txt.replace(min, max, phrase);
			editText.requestFocus();
			editText.setSelection(min + phrase.length());
		}
	};
	
	public static class ViewTag {
		public boolean flag;
		// 图片原图uri
		public Uri imageUri;
		// 文件全路径
		public String path;
		// 录音时长, 在图片处理中当滤镜类型
		public int  duration;
		// View的id
		public int  id;
	}

    @Override
    public void onMediaPlay() {
        
    }

    @Override
    public void onMediaPause() {
        
    }

    @Override
    public void onMediaRelease() {
        
    }

    @Override
    public void onMediaCompletion() {
        mAnimationDrawable.stop();
    }
}
